import React, { useState, useEffect, useRef } from 'react';
import { getConsoleWebSocketURL } from '../api/client';

interface ConsoleTerminalProps {
  domainUUID: string;
  consoleType?: 'console' | 'serial' | 'parallel' | 'channel';
  isOpen: boolean;
  onClose: () => void;
}

const ConsoleTerminal: React.FC<ConsoleTerminalProps> = ({
  domainUUID,
  consoleType = 'console',
  isOpen,
  onClose
}) => {
  const [connected, setConnected] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [terminalContent, setTerminalContent] = useState<string>('');
  const [inputValue, setInputValue] = useState<string>('');
  const wsRef = useRef<WebSocket | null>(null);
  const terminalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (isOpen && domainUUID) {
      connectToConsole();
    } else {
      disconnect();
    }

    return () => {
      disconnect();
    };
  }, [isOpen, domainUUID, consoleType]);

  useEffect(() => {
    // 自动滚动到底部
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [terminalContent]);

  const connectToConsole = async () => {
    if (connecting || connected) return;

    setConnecting(true);
    setError(null);
    setTerminalContent('');

    try {
      // 直接使用新的API端点构建WebSocket URL
      const wsUrl = getConsoleWebSocketURL(domainUUID, consoleType);
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;

      ws.onopen = () => {
        console.log('Console WebSocket connected');
        setConnected(true);
        setConnecting(false);
        setTerminalContent('>>> Console connected successfully\r\n');
      };

      ws.onmessage = (event) => {
        const data = event.data;
        if (typeof data === 'string') {
          setTerminalContent(prev => prev + data);
        } else if (data instanceof Blob) {
          // 处理二进制数据
          const reader = new FileReader();
          reader.onload = () => {
            setTerminalContent(prev => prev + reader.result as string);
          };
          reader.readAsText(data);
        }
      };

      ws.onerror = (error) => {
        console.error('Console WebSocket error:', error);
        setError('Connection error occurred');
        setConnecting(false);
      };

      ws.onclose = (event) => {
        console.log('Console WebSocket closed:', event.code, event.reason);
        setConnected(false);
        setConnecting(false);
        if (event.code !== 1000) {
          setTerminalContent(prev => prev + `\r\n>>> Connection closed: ${event.reason || 'Unknown reason'}\r\n`);
        }
      };
    } catch (err) {
      console.error('Failed to create WebSocket:', err);
      setError('Failed to create connection');
      setConnecting(false);
    }
  };

  const disconnect = () => {
    if (wsRef.current) {
      wsRef.current.close(1000, 'User closed connection');
      wsRef.current = null;
    }
    setConnected(false);
    setConnecting(false);
  };

  const sendInput = (input: string) => {
    if (wsRef.current && connected) {
      try {
        wsRef.current.send(input);
        // 在终端中显示用户输入
        setTerminalContent(prev => prev + input);
      } catch (err) {
        console.error('Failed to send data:', err);
        setError('Failed to send data to console');
      }
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (inputValue.trim()) {
      sendInput(inputValue + '\r\n');
      setInputValue('');
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e as any);
    }
  };

  const clearTerminal = () => {
    setTerminalContent('');
  };

  const reconnect = () => {
    disconnect();
    setTimeout(() => connectToConsole(), 500);
  };

  if (!isOpen) {
    return null;
  }

  return (
    <div className="console-terminal-modal">
      <div className="console-modal-overlay" onClick={onClose}>
        <div className="console-modal-content" onClick={(e) => e.stopPropagation()}>
          <div className="console-modal-header">
            <div className="console-header-info">
              <h2>Console Terminal - {domainUUID}</h2>
              <span className="console-type-badge">{consoleType}</span>
            </div>
            <div className="console-header-actions">
              <span className={`connection-status ${connected ? 'connected' : 'disconnected'}`}>
                {connected ? '🟢 Connected' : connecting ? '🟡 Connecting...' : '🔴 Disconnected'}
              </span>
              <button className="console-close-btn" onClick={onClose} title="Close">
                ✕
              </button>
            </div>
          </div>

          <div className="console-modal-body">
            {error && (
              <div className="console-error">
                <div className="error-icon">⚠️</div>
                <h3>Console Error</h3>
                <p>{error}</p>
                <div className="error-actions">
                  <button onClick={reconnect} className="primary">
                    Reconnect
                  </button>
                </div>
              </div>
            )}

            <div className="terminal-container">
              <div className="terminal-toolbar">
                <div className="terminal-controls">
                  <button
                    onClick={clearTerminal}
                    className="secondary"
                    title="Clear terminal"
                  >
                    🗑️ Clear
                  </button>
                  <button
                    onClick={reconnect}
                    className="secondary"
                    disabled={connecting}
                    title="Reconnect to console"
                  >
                    {connecting ? '🔄 Reconnecting...' : '🔄 Reconnect'}
                  </button>
                </div>
              </div>

              <div className="terminal-display-container">
                <div className="terminal-display" ref={terminalRef}>
                <pre className="terminal-content">{terminalContent}</pre>
              </div>
              </div>

              <form className="terminal-input-form" onSubmit={handleSubmit}>
                <textarea
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder={connected ? "Type command here..." : "Not connected"}
                  disabled={!connected}
                  className="terminal-input"
                  rows={3}
                />
                <div className="terminal-input-actions">
                  <button
                    type="submit"
                    className="primary"
                    disabled={!connected || !inputValue.trim()}
                  >
                    Send
                  </button>
                </div>
              </form>
            </div>
          </div>

          <div className="console-modal-footer">
            <div className="terminal-info">
              <span>Console Type: {consoleType}</span>
              <span className="separator">|</span>
              <span>Domain UUID: {domainUUID}</span>
            </div>
            <button onClick={onClose} className="secondary">
              Close
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .console-terminal-modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 1000;
        }

        .console-modal-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }

        .console-modal-content {
          background: #1e1e1e;
          border-radius: 8px;
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
          max-width: 95vw;
          max-height: 95vh;
          width: 900px;
          height: 600px;
          display: flex;
          flex-direction: column;
          color: white;
        }

        .console-modal-header {
          padding: 15px 20px;
          border-bottom: 1px solid #333;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .console-header-info {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .console-modal-header h2 {
          margin: 0;
          font-size: 1.3em;
          color: #fff;
        }

        .console-type-badge {
          background: #007bff;
          color: white;
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 0.8em;
          font-weight: bold;
        }

        .console-header-actions {
          display: flex;
          align-items: center;
          gap: 15px;
        }

        .connection-status {
          font-size: 0.9em;
          font-weight: bold;
        }

        .connection-status.connected {
          color: #28a745;
        }

        .connection-status.disconnected {
          color: #dc3545;
        }

        .console-close-btn {
          background: none;
          border: none;
          color: white;
          font-size: 1.5em;
          cursor: pointer;
          padding: 5px;
          border-radius: 4px;
        }

        .console-close-btn:hover {
          background: #333;
        }

        .console-modal-body {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        .console-error {
          background: #dc3545;
          color: white;
          padding: 15px;
          margin: 10px;
          border-radius: 6px;
          text-align: center;
        }

        .console-error .error-icon {
          font-size: 2em;
          margin-bottom: 10px;
        }

        .console-error h3 {
          margin: 0 0 5px 0;
        }

        .console-error p {
          margin: 0 0 15px 0;
        }

        .terminal-container {
          flex: 1;
          display: flex;
          flex-direction: column;
          padding: 0;
          overflow: hidden;
        }

        .terminal-toolbar {
          padding: 10px 15px;
          border-bottom: 1px solid #333;
        }

        .terminal-controls {
          display: flex;
          gap: 10px;
        }

        .terminal-display-container {
          flex: 1;
          overflow: hidden;
          background: #000;
        }

        .terminal-display {
          height: 100%;
          overflow: auto;
          padding: 10px;
          font-family: 'Courier New', monospace;
          font-size: 14px;
          line-height: 1.2;
        }

        .terminal-content {
          margin: 0;
          color: #00ff00;
          white-space: pre-wrap;
          word-wrap: break-word;
        }

        .terminal-input-form {
          padding: 15px;
          border-top: 1px solid #333;
        }

        .input-container {
          display: flex;
          gap: 10px;
          align-items: flex-end;
        }

        .terminal-input {
          flex: 1;
          background: #000;
          border: 1px solid #444;
          color: #00ff00;
          font-family: 'Courier New', monospace;
          font-size: 14px;
          padding: 8px;
          border-radius: 4px;
          resize: vertical;
          min-height: 40px;
          max-height: 120px;
        }

        .terminal-input:focus {
          outline: none;
          border-color: #007bff;
        }

        .terminal-input:disabled {
          background: #333;
          color: #666;
        }

        .send-button {
          background: #007bff;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
          height: 40px;
        }

        .send-button:hover:not(:disabled) {
          background: #0056b3;
        }

        .send-button:disabled {
          background: #666;
          cursor: not-allowed;
        }

        .console-modal-footer {
          padding: 10px 20px;
          border-top: 1px solid #333;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .console-info {
          font-size: 0.9em;
          color: #aaa;
        }

        button {
          padding: 8px 16px;
          border: 1px solid #555;
          border-radius: 4px;
          background: #333;
          color: white;
          cursor: pointer;
          font-size: 0.9em;
        }

        button:hover:not(:disabled) {
          background: #444;
        }

        button:disabled {
          background: #222;
          color: #666;
          cursor: not-allowed;
        }

        button.primary {
          background: #007bff;
          border-color: #007bff;
        }

        button.primary:hover:not(:disabled) {
          background: #0056b3;
        }

        button.secondary {
          background: #6c757d;
          border-color: #6c757d;
        }

        button.secondary:hover:not(:disabled) {
          background: #545b62;
        }
      `}</style>
    </div>
  );
};

export default ConsoleTerminal;